package com.flightgame.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.flightgame.hibernate.Airport;
import com.flightgame.hibernate.AirportDao;
import com.flightgame.hibernate.Flight;
import com.flightgame.hibernate.FlightDao;
import com.flightgame.hibernate.Item;
import com.flightgame.hibernate.ItemDao;
import com.flightgame.hibernate.Ownership;
import com.flightgame.hibernate.OwnershipDao;
import com.flightgame.hibernate.User;
import com.flightgame.hibernate.UserDao;
import com.flightgame.tools.Builder;
import com.flightgame.tools.Utils;

@Service
public class GameServices {
	@Autowired
	private UserDao userDao;
	@Autowired
	private OwnershipDao ownershipDao;
	@Autowired
	private ItemDao itemDao;
	@Autowired
	private AirportDao airportDao;

	public User addNewUser(String username,String password){
		User user=null;
		if(userDao.isUserExist(username) == false){
			user = new User();
			user.setUsername(username);
			user.setCredits(1000000);
			userDao.addUser(user);
		}
		return user;
	}
	
	public boolean isUserExist(String username){
		return userDao.isUserExist(username);
	}

	public int buyItem(String username,String itemname,double lat,double lon,String airportCode){
		User user = userDao.getUser(username);
		Utils util = new Utils();
		Builder builder = new Builder();
		Item item = itemDao.getItem(itemname);
		double remain = user.getCredits() - item.getPrice();
		List <Ownership> ownershipsAround = ownershipDao.getOwnershipsOnBoundedCoordinates(lat -1, lat + 1, lon -1, lon + 1);
		
		if(ownershipsAround.size() > 0) return util.OWNERSHIP_AROUND;
		else if(remain < 0) return util.INSUFFICIENT_CREDITS;
		
		if(airportCode != null){
			Airport airport = airportDao.getAirportByCode(airportCode);
			lat = airport.getLat();
			lon = airport.getLon();
		}

		Ownership ownership = builder.ownershipBuilder(username, itemname, lat, lon, airportCode,util.setDefaultParameters(item.getType()));
		ownershipDao.addOwnership(ownership);
		userDao.decreaseIncreaseUserCredit(username,-1 * item.getPrice());

		return util.SUCCESS;
	}
	
	public void sellOwnershipToUser(int ownershipId,String usernameSellTo,int price){
		Ownership ownership = ownershipDao.getOwnership(ownershipId);
		
		userDao.transferCredit(ownership.getUsername(),usernameSellTo,price);
		
		ownershipDao.changeOwnershipUsername(ownershipId,usernameSellTo);
	}

}